package com.wswy.wzcx.module.base

import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.annotation.Keep
import android.support.v4.util.SparseArrayCompat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.che.libcommon.ui.BaseFragment
import com.wswy.wzcx.model.core.EventNormal
import com.wswy.wzcx.model.core.postEvent
import com.wswy.wzcx.statistics.StatTools
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

open class CBaseFragment : BaseFragment() {

    protected fun <T: ViewModel> provideViewModel(modelClass:Class<T>):T{
        return ViewModelProviders.of(this).get(modelClass)
    }

    protected fun <T: ViewModel> provideViewModelFromActivity(modelClass:Class<T>):T{
        return ViewModelProviders.of(activity!!).get(modelClass)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        if (getContentLayoutId() != 0){
            return inflater.inflate(getContentLayoutId(),container,false)
        }
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    open protected fun getContentLayoutId() : Int = 0


    inline fun sendClickEvent(id:String){
        StatTools.sendClick(context, id)
    }

    private lateinit var events : SparseArrayCompat<((Any?)->Unit)>

    @Keep
    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun onEventCodeNormal(event:EventNormal){
        if(this::events.isInitialized){
            events.get(event.code)?.invoke(event.code)
        }
    }
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        if (!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this)
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        if (EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this)
        }
    }

    fun registerEvent(code:Int,callback:((Any?)->Unit)?){
        if (!this::events.isInitialized){
            events = SparseArrayCompat()
        }
        events.put(code,callback)
    }

}